package com.bfsuol.yihang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/set/{key}/{value}")
    public String setKey(@PathVariable("key") String key, @PathVariable("value") Object value) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.opsForValue().setIfAbsent("setNx-a", "setNx-b");
        return "success";
    }

    @GetMapping("/get/{key}")
    public Object getKey(@PathVariable("key") String key) {
        System.out.println(redisTemplate.opsForValue().get("setNx-a"));
        return redisTemplate.opsForValue().get(key);
    }

    @GetMapping("/inc/get/{key}")
    public String incKey(@PathVariable("key") String key) {
        Long a = redisTemplate.opsForValue().increment(key,  10);
        redisTemplate.expire(key,60, TimeUnit.SECONDS);
        System.out.println(a);
        return a.toString();
    }

    @GetMapping("/getAndSet/{key}/{value}")
    public String getAndSetKey(@PathVariable("key") String key,@PathVariable("value") String value) {
        System.out.println(redisTemplate.opsForValue().getAndSet("getAndSet-a",value));
        return redisTemplate.opsForValue().get("getAndSet-a").toString();
    }

}
